<template>
  <div>
    <div class="search">
      <input
        v-model="keyword"
        type="text"
        placeholder="输入城市名或拼音"
        class="search-input"
      />
    </div>
    <div class="search-content" v-show="keyword" ref="wrapper">
      <ul>
        <li
          class="search-item border-bottom"
          v-for="item of list"
          :key="item.id"
          @click="change(item.name)"
        >
          {{ item.name }}
        </li>
        <li v-show="!list.length">没有找到可匹配的城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
import { useStore } from "vuex";
import { computed, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
export default {
  name: "CitySearch",
  props: {
    cities: Object,
  },
  setup(props) {
    const { keyword, list } = useKeywordLogic(props);
    const { change } = useStoreAndRouter();
    const { wrapper } = useScrollWapper();

    return { keyword, change, wrapper, list };
  },
};
function useKeywordLogic(props) {
  const keyword = ref("");
  let timer = null;
  const list = ref([]);
  watch(keyword, (newValue) => {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    if (!newValue) {
      list.value = [];
      return;
    }
    timer = setTimeout(() => {
      const result = [];
      for (let item in props.cities) {
        for (let i of props.cities[item]) {
          if (i.spell.includes(newValue) || i.name.includes(newValue)) {
            result.push(i);
          }
        }
      }
      list.value = result;
    }, 100);
  });
  return { keyword, list };
}

function useStoreAndRouter() {
  const store = useStore();
  const router = useRouter();
  function change(value) {
    store.commit("changeCity", value);
    //keyword.value = ''
    router.push("/");
  }
  return { change };
}

function useScrollWapper() {
  const wrapper = ref(null);
  onMounted(() => {
    new Bscroll(wrapper.value, {
      click: true,
    });
  });
  return { wrapper };
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl';

.search {
  height: 0.72rem;
  background: $bgColor;
  padding: 0 0.1rem;

  .search-input {
    width: 100%;
    border-radius: 0.06rem;
    height: 0.62rem;
    text-align: center;
    color: #666;
  }
}

.search-content {
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fdfdfd;
  z-index: 1;

  .search-item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    color: #666;
  }
}
</style>>